/**
 * 
 */
package org.thinkinbunny.financial.http;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.thinkinbunny.financial.billentity.UserEntiry;
import org.thinkinbunny.financial.config.Config;
import org.thinkinbunny.financial.util.Log;

/**
 * @author ThinkinBunny
 * @see 此类包括3个方法；sendPostRequest:发送请求
 */
public class HttpTools {

	public static JSONArray HttpPostData(JSONArray jsonArray,
			String functionId, UserEntiry userEntiry) {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			String uri = Config.getHost() + "ApiUpdateFromClient?functionId="
					+ functionId;
			HttpPost httppost = new HttpPost(uri);
			ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
			httppost.setHeader("Content-Type", "application/json");
			httppost.setHeader("charset", "utf-8");

			JSONObject obj = new JSONObject();
			obj.put("username", userEntiry.getUsername());
			obj.put("password", userEntiry.getPassword());
			obj.put("message", jsonArray);
			// obj.put("parentId", "your parentid");
			Log.i("HttpTools", obj.toString());
			// nameValuePair.add(new BasicNameValuePair("message", jsonArray
			// .toString()));
			//

			httppost.setEntity(new StringEntity(obj.toString(), "utf-8"));
			HttpResponse response;

			response = httpclient.execute(httppost);
			// 检验状态码，如果成功接收数据
			jsonArray = null;
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				String rev = EntityUtils
						.toString(response.getEntity(), "utf-8");// 返回json格式：
																	// {"id":
																	// "27JpL~j4vsL0LX00E00005","version":
																	// "abc"}
				// obj = new JSONObject(rev);
				// String id = obj.getString("id");
				// String version = obj.getString("version");
				Log.i("responnn:>>>", functionId+rev);
				JSONObject json = new JSONObject(rev);

				jsonArray = new JSONArray();
				jsonArray = json.getJSONArray("message");
			}
		} catch (ClientProtocolException e) {
			Log.e("HttpTools", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("HttpTools", e.getMessage());
			return null;
		} catch (Exception e) {
			Log.e("HttpTools", e.getMessage());
			e.printStackTrace();
			return null;
		}
		return jsonArray;
	}

	public static UserEntiry HttpGetDataCheckUser(String functionId,
			UserEntiry userEntiry) {
		JSONObject jsonArray;
		try {
			HttpClient httpclient = new DefaultHttpClient();
			String uri = Config.getHost() + "ApiRegister?functionId="
					+ functionId;
			HttpPost httppost = new HttpPost(uri);
			ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
			httppost.setHeader("Content-Type", "application/json");
			httppost.setHeader("charset", "utf-8");

			JSONObject obj = new JSONObject();
			obj.put("username", userEntiry.getUsername());
			obj.put("password", userEntiry.getPassword());
			obj.put("email", userEntiry.getEmail());
			httppost.setEntity(new StringEntity(obj.toString(), "utf-8"));
			HttpResponse response;

			response = httpclient.execute(httppost);
			// 检验状态码，如果成功接收数据
			jsonArray = null;
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				String rev = EntityUtils
						.toString(response.getEntity(), "utf-8");// 返回json格式：
																	// {"id":
																	// "27JpL~j4vsL0LX00E00005","version":
																	// "abc"}
				// obj = new JSONObject(rev);
				// String id = obj.getString("id");
				// String version = obj.getString("version");
				Log.i("responnn:>>>", rev);
				JSONObject json = new JSONObject(rev);

				jsonArray = new JSONObject();
				jsonArray = json.getJSONObject("message");
				if (functionId.equals("login")) {
					if (!(jsonArray.getString("username").equals(
							userEntiry.getUsername()) && jsonArray.get(
							"password").equals(userEntiry.getPassword()))) {

						return null;
					}
				}

			}
		} catch (ClientProtocolException e) {
			Log.e("HttpTools", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("HttpTools", e.getMessage());
			return null;
		} catch (Exception e) {

			e.printStackTrace();
			return null;
		}
		return userEntiry;
	}

	public static JSONArray HttpGetDataCheckVer(String version) {
		JSONArray jsonArray;
		try {
			HttpClient httpclient = new DefaultHttpClient();
			String uri = Config.getHostForUpdate();
			//String uri = Config.getHost() + "APiCheckVersion?" + version;
			HttpPost httppost = new HttpPost(uri);
			HttpGet httpGet=new HttpGet(uri);
			ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
			httpGet.setHeader("Content-Type", "application/json");
			httpGet.setHeader("charset", "utf-8");

			// JSONObject obj = new JSONObject();
			// obj.put("message", jsonArray);
			// obj.put("parentId", "your parentid");
			// Log.i("HttpTools", obj.toString());
			// nameValuePair.add(new BasicNameValuePair("message", jsonArray
			// .toString()));
			//
			// httppost.setEntity(new StringEntity(obj.toString(),"utf-8"));
			HttpResponse response;

			response = httpclient.execute(httpGet);
			// 检验状态码，如果成功接收数据
			jsonArray = null;
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				String rev = EntityUtils
						.toString(response.getEntity(), "utf-8");// 返回json格式：
																	// {"id":
																	// "27JpL~j4vsL0LX00E00005","version":
																	// "abc"}
				// obj = new JSONObject(rev);
				// String id = obj.getString("id");
				// String version = obj.getString("version");
				Log.i("responnn:>>>", rev);
				JSONObject json = new JSONObject(rev);

				jsonArray = new JSONArray();
				jsonArray = json.getJSONArray("message");
			}
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			return null;
		} catch (Exception e) {

			e.printStackTrace();
			return null;
		}
		return jsonArray;
	}

	// sendPostRequest ，接受params，通过post请求发送
	public static JSONArray HttpGetData(String functionId, UserEntiry userEntiry) {
		JSONArray jsonArray;
		try {
			HttpClient httpclient = new DefaultHttpClient();
			String uri = Config.getHost() + "ApiUpdateToClient?functionId="
					+ functionId;
			HttpPost httppost = new HttpPost(uri);
			ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
			httppost.setHeader("Content-Type", "application/json");
			httppost.setHeader("charset", "utf-8");
			JSONObject obj = new JSONObject();
			obj.put("username", userEntiry.getUsername());
			obj.put("password", userEntiry.getPassword());
			// JSONObject obj = new JSONObject();
			// obj.put("message", jsonArray);
			// obj.put("parentId", "your parentid");
			// Log.i("HttpTools", obj.toString());
			// nameValuePair.add(new BasicNameValuePair("message", jsonArray
			// .toString()));
			//
			httppost.setEntity(new StringEntity(obj.toString(), "utf-8"));
			HttpResponse response;
			Log.i("body:>>>", functionId+obj.toString());
			response = httpclient.execute(httppost);
			// 检验状态码，如果成功接收数据
			jsonArray = null;
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				String rev = EntityUtils
						.toString(response.getEntity(), "utf-8");// 返回json格式：
																	// {"id":
																	// "27JpL~j4vsL0LX00E00005","version":
																	// "abc"}
				// obj = new JSONObject(rev);
				// String id = obj.getString("id");
				// String version = obj.getString("version");
				Log.i("responnn:>>>", functionId+rev);
				JSONObject json = new JSONObject(rev);

				jsonArray = new JSONArray();
				jsonArray = json.getJSONArray("message");
			}
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			return null;
		} catch (Exception e) {

			e.printStackTrace();
			return null;
		}
		return jsonArray;
	}

	// sendPostRequest ，接受params，通过post请求发送
	// public static boolean sendPostRequest(String path,
	// JSONArray jsonArray) throws Exception {
	// // StringBuilder sb = new StringBuilder();
	// // if (params != null && !params.isEmpty()) {
	// // for (Map.Entry<String, String> entry : params.entrySet()) {
	// // sb.append(entry.getKey()).append('=')
	// // .append(URLEncoder.encode(entry.getValue(), enc))
	// // .append('&');
	// // }
	// // sb.deleteCharAt(sb.length() - 1);
	// // }
	// byte[] entitydata = jsonArray.toString().getBytes();// 得到实体的二进制数据
	// URL url = new URL("http://192.168.1.106:8084/jdreader/GetAccountInfo");
	// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	// conn.setRequestMethod("POST");
	// conn.setConnectTimeout(5 * 1000);
	// conn.setDoOutput(true);// 如果通过post提交数据，必须设置允许对外输出数据
	// // Content-Type: application/x-www-form-urlencoded
	// // Content-Length: 38
	// conn.setRequestProperty("Content-Type",
	// "application/json");
	// conn.setRequestProperty("Content-Length",
	// String.valueOf(entitydata.length));
	// OutputStream outStream = conn.getOutputStream();
	//
	//
	// outStream.flush();
	// outStream.close();
	// // HttpResponse response;
	// //
	// // response = httpclient.execute(httppost);
	// if (conn.getResponseCode() == 200) {
	// // 检测发送是否完成，如果错误返回代码不是200
	// // String rev =
	// EntityUtils.toString(response.getEntity(),"utf-8");//返回json格式： {"id":
	// "27JpL~j4vsL0LX00E00005","version": "abc"}
	// // // obj = new JSONObject(rev);
	// // // String id = obj.getString("id");
	// // // String version = obj.getString("version");
	// // Log.i("responnn:>>>",rev);
	// return true;
	// }
	// return false;
	// }

	// public static boolean sendPostRequest(String path,
	// Map<String, String> params, String enc) throws Exception {
	// StringBuilder sb = new StringBuilder();
	// if (params != null && !params.isEmpty()) {
	// for (Map.Entry<String, String> entry : params.entrySet()) {
	// sb.append(entry.getKey()).append('=')
	// .append(URLEncoder.encode(entry.getValue(), enc))
	// .append('&');
	// }
	// sb.deleteCharAt(sb.length() - 1);
	// }
	// byte[] entitydata = sb.toString().getBytes();// 得到实体的二进制数据
	// URL url = new URL(path);
	// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	// conn.setRequestMethod("POST");
	// conn.setConnectTimeout(5 * 1000);
	// conn.setDoOutput(true);// 如果通过post提交数据，必须设置允许对外输出数据
	// // Content-Type: application/x-www-form-urlencoded
	// // Content-Length: 38
	// conn.setRequestProperty("Content-Type",
	// "application/x-www-form-urlencoded");
	// conn.setRequestProperty("Content-Length",
	// String.valueOf(entitydata.length));
	// OutputStream outStream = conn.getOutputStream();
	// outStream.write(entitydata);
	// outStream.flush();
	// outStream.close();
	// if (conn.getResponseCode() == 200) {
	// // 检测发送是否完成，如果错误返回代码不是200
	// return true;
	// }
	// return false;
	// }

	// InputStream 用于把server端产生的数据流（数据库信息）接受为inputstream，用于xml数据解析
	public static InputStream getUpdateInputStream(String functionId) {
		InputStream retInputStream = null;
		URL url;
		try {

			url = new URL(
					"http://192.168.1.101:8080/UserManaSys/AndroidResponseServlt?functionId="
							+ functionId);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			conn.setRequestMethod("POST");
			conn.setConnectTimeout(3 * 1000);
			retInputStream = conn.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}

		return retInputStream;

	}

	/* DownAllPictures下载图片方法，接受图片名，构建下载路径下载 */
	// public static void DownAllPictures(String picName) {
	//
	// InputStream retInputStream = null;
	// URL url;
	// File file = new File("/mnt/sdcard/foods/");
	// if (!file.exists()) {
	// file.mkdir();
	// // 检测是否存在foods目录，没有则创建
	// }
	// file = new File("/mnt/sdcard/foods/" + picName);
	// if (!file.exists()) {// 检测图片是否存在，存在则不下载，否则继续下载
	// try {
	// url = new URL("http://192.168.1.101:8080/UserManaSys/Images/"
	// + picName);
	// HttpURLConnection conn = (HttpURLConnection) url
	// .openConnection();
	// conn.setRequestMethod("POST");
	// conn.setConnectTimeout(3 * 10000);
	// retInputStream = conn.getInputStream();
	// ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
	// int ch;
	// while ((ch = retInputStream.read()) != -1) {
	// bytestream.write(ch);
	// }
	// byte imgdata[] = bytestream.toByteArray();
	//
	// File pic = new File("/mnt/sdcard/foods/" + picName);
	// //System.out.println("len:" + imgdata.length);
	// FileOutputStream outputStream = new FileOutputStream(pic);
	// outputStream.write(imgdata);
	//
	// outputStream.flush();
	// outputStream.close();
	//
	// } catch (MalformedURLException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	//
	// }
	//
	// }

	/**
	 * InputStream转String 这里用的方法和下面一个函数方法不同，看官看到下面的函数自然会明白
	 * 
	 * @param is
	 * @param encode
	 * @return
	 */
	public static String stream2string(InputStream is, String encode) {
		if (is != null) {
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, encode));
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				return sb.toString();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	/**
	 * InputStream转jsonarray
	 * 此处在处理InputStream时所用的方法和上面一个函数不同，只是多列出一个可用方法，实际使用时，请考虑一下效率问题
	 * 至于转成jsonarray的笨办法只是由于个人需求，接口也是自己写的，有十足把握不会导致出错，各位看官莫怪，轻易不要这样干
	 * 
	 * @param is
	 * @return
	 */
	// public static String stream2jarray(InputStream is) {
	// if (is != null) {
	// StringBuffer sb = new StringBuffer();
	// byte[] b = new byte[4096];
	// try {
	// for(int n;(n=is.read(b))!=-1;){
	// sb.append(new String(b,0,n));
	// }
	// is.close();
	// if(sb.charAt(0) == '{'){
	// return "["+sb.toString()+"]";
	// }
	// else{
	// return sb.toString();
	// }
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	// return "";
	// }
	//
	/**
	 * InputStream转jsonobject 转jsonobject时同样使用了笨办法，轻易不要照我这样用
	 * 
	 * @param is
	 * @return
	 */
	public static String stream2jobject(InputStream is) {
		if (is != null) {
			StringBuffer sb = new StringBuffer();

			byte[] b = new byte[4096];
			try {
				for (int n; (n = is.read(b)) != -1;) {
					sb.append(new String(b, 0, n));
				}
				is.close();
				if (sb.charAt(0) == '[') {
					return "{\"jarray\":" + sb.toString() + "}";
				} else {
					return sb.toString();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	public static String stream2string(InputStream is) {
		return stream2string(is, "utf-8");
	}

	/**
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] stream2byte(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}
}
